<template>
  <data-table-app-page>
    <div slot="toolbar">
      <el-form inline :model="searchForm">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.realName" clearable style="width: 90px"></el-input>
        </el-form-item>
        <el-form-item label="老年卡证号">
          <el-input v-model="searchForm.elderlyCard" clearable style="width: 160px"></el-input>
        </el-form-item>
        <el-form-item label="设备号/卡号">
          <el-input v-model="searchForm.deviceCode" clearable style="width: 170px"></el-input>
        </el-form-item>
        <el-form-item label="用户类型">
          <type-select
            v-model="searchForm.userTypes"
            :items="DictMan.items('user.type')"
            multiple
            collapse-tags
            style="width: 174px"
          />
        </el-form-item>
        <el-form-item>
          <data-table-query-button :query-params="getQueryParams" @query="onQuery" />
        </el-form-item>
        <el-form-item>
          <el-badge type="primary" :value="nonEmptyItemNumberInQuerier || null">
            <el-button
              type="primary"
              plain
              icon="el-icon-more"
              @click="onQuerierShowClick"
            >
              更多查询
            </el-button>
          </el-badge>
        </el-form-item>
      </el-form>
      <el-button
        v-auth="'user.add'"
        type="primary"
        icon="el-icon-plus"
        @click="onAddClick"
      >
        增加
      </el-button>
      <el-dropdown
        v-if="'user.add'"
        type="default"
        trigger="hover"
        @command="onImportCommandClick($event)"
        @click="onAddClick">
        <el-button>
          <i class="el-icon-upload2"></i>
          <span>导入</span>
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <!--<el-dropdown-item command="oldman">老人用户</el-dropdown-item>-->
          <el-dropdown-item command="device">设备用户</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button
        type="default"
        icon="el-icon-download"
        @click="onExportClick"
      >
        导出
      </el-button>
    </div>
    <data-table
      ref="table"
      url="/api/user/listUser"
      row-key="id"
      lazy
      timing
    >
      <el-table-column prop="realName" label="姓名" width="70" show-overflow-tooltip v-slot="{row}">
        {{row.realName || '未知'}}
      </el-table-column>
      <el-table-column prop="aliasName" label="昵称" width="70" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sex" label="性别" width="48" v-slot="{row}">
        {{DictMan.itemMap('user.gender')[row.sex]}}
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="48"></el-table-column>
      <el-table-column prop="idcard" label="身份证号码" width="174" v-slot="{row}">
        {{row.idcard || '未知'}}
      </el-table-column>
      <el-table-column prop="orgName" label="社区" width="110" show-overflow-tooltip></el-table-column>
      <el-table-column prop="userType" label="用户类型" width="90" v-slot="{row}">
        {{DictMan.itemMap('user.type')[row.userType]}}
      </el-table-column>
      <el-table-column prop="deviceCode" label="设备号/卡号" width="150" v-slot="{row}">
        {{[2,9].includes(row.userType) ? row.deviceCode : '-'}}
      </el-table-column>
      <el-table-column prop="elderlyCard" label="老年卡证号" width="140" show-overflow-tooltip v-slot="{row}">
        {{row.elderlyCard || '无'}}
      </el-table-column>
      <el-table-column prop="elderlyCardType" label="办卡类型" width="80" v-slot="{row}">
        {{row.elderlyCardType ? DictMan.itemMap("user.elderlyCardType")[row.elderlyCardType] : '-'}}
      </el-table-column>
      <el-table-column v-if="cityAllowanceColVisible" prop="cityAllowanceEvalScore" label="评估分数" width="80" ></el-table-column>
      <el-table-column v-if="cityAllowanceColVisible" prop="cityAllowanceEvalStatus" label="评估状态" width="80" v-slot="{row}">
        {{DictMan.itemMap('evalOldman.evalState')[row.cityAllowanceEvalStatus]}}
      </el-table-column>
      <el-table-column v-if="cityAllowanceColVisible" prop="cityAllowanceAmount" label="拟享受市补贴" width="110"></el-table-column>
      <el-table-column prop="registerTime" label="注册时间" width="152"></el-table-column>
      <el-table-column v-if="$auth('')" label="操作" :min-width="opColVisible ? 214 : 0" fixed="right" v-slot="{row}">
        <template v-if="opColVisible">
          <el-button
            v-auth="'details'"
            type="warning"
            plain
            @click="onDetailsClick(row)"
          >
            详情
          </el-button>
          <el-button
            v-auth="'user.update'"
            type="danger"
            plain
            @click="onUpdateClick(row)"
            style="margin-left:0px"
            >修改</el-button>
          <user-operations
            ref="userOperations"
            :user="row"
            :openTab="openTab" :table="() => $refs.table"
            style="margin-left: 0px"
          />
        </template>
        <div v-else style="height: 32px"></div>
      </el-table-column>
    </data-table>

    <user-querier
      ref="userQuerier" 
      @hook:mounted="onQuerierMounted"
      @change="onQuerierChange"
      @query="onQuery"
      @reset="onQueryReset"
    />
    <user-import-dialog ref="userImportDialog" />
  </data-table-app-page>
</template>


<script>
import qs from 'qs';
import _ from 'underscore';
import UserOperations from './UserOperations';

export default {
  pageProps: {
    title: '用户管理'
  },
  components: {
    UserOperations,
    UserQuerier: () => import('./UserQuerier.vue'),
    UserImportDialog: () => import('./UserImportDialog.vue')
  },
  data() {
    this.searchFormInitialValues = {
      realName: '',
      deviceCode: '',
      elderlyCard: '',
      userTypes: []
    };
    return {
      permission: '/smart_info_center/life/user/user',
      searchForm: {
        ...this.searchFormInitialValues,
        ...this.getPageParams().query
      },
      nonEmptyItemNumberInQuerier: 0,
      cityAllowanceColVisible: false,
      opColVisible: true
    }
  },
  computed: {
    pageParams() {
      return this.getPageParams();
    }
  },
  watch: {
    $params(newParams, oldParams) {
      if (newParams.query) {
        this.$refs.userQuerier.reset();
        this.searchForm = {...this.searchFormInitialValues, ...this.getPageParams().query};
        if (Object.keys(this.getMoreQueryParams()).length > 0) {
          this.onQuerierMounted();
        } else {
          this.$refs.table.query(this.getQueryParams());
        }
      }
    }
  },
  mounted() {
    // 如果传递了query，不由此处控制查询
    if (!this.pageParams.query) {
      this.$refs.table.query(this.getQueryParams());
    }
  },
  methods: {
    getQueryParams() {
      let queryParams = {...this.searchForm};
      for (let key in queryParams) {
        // 如果是数组，转换为CSV
        if (queryParams[key] instanceof Array) {
          queryParams[key] = queryParams[key].join(',');
        }
      }
      return queryParams;
    },
    getMoreQueryParams() {
      return _.omit(this.pageParams.query, Object.keys(this.searchFormInitialValues));
    },
    onQuerierMounted() {
      if (this.pageParams.query) {
        // 如果传递了在列表页面没有的查询条件，则需要打开高级查询器
        if (Object.keys(this.getMoreQueryParams()).length > 0) {
          this.onQuerierShowClick();
          this.$nextTick(() => {
            this.$refs.userQuerier.query();
          });
        } else {
          this.$refs.table.query(this.getQueryParams());
        }
      }
    },
    onQuerierChange({nonEmptyFieldCount, queryParams}) {
      this.nonEmptyItemNumberInQuerier = nonEmptyFieldCount;
    },
    onQuery(queryParams) {
      this.queryed = true;
      this.changeCityAllowanceColVisible(queryParams);
    },
    onQuerierShowClick() {
      this.$refs.userQuerier.show({
        values: this.searchForm,
        table: this.$refs.table,
        onClose: (form) => {
          for (let key in form) {
            this.$set(this.searchForm, key, form[key]);
          }
          this.changeCityAllowanceColVisible(form);
        }
      });
    },
    onQueryReset() {
      if (this.queryed) {
        this.$refs.table.query(this.getQueryParams());
      }
    },
    onAddClick() {
      this.pushPage({
        path: '/user/register',
        key: 'add',
        params: {
          mode: 'add',
          onSuccess: () => {
            this.$refs.table.reloadCurrentPage();
          }
        }
      });
    },
    onUpdateClick(user) {
      this.pushPage({
        path: '/user/register',
        key: user.id,
        params: {
          mode: 'update',
          user,
          onSuccess: () => {
            this.table && this.table().reloadCurrentPage();
          }
        }
      });
    },
    onImportCommandClick(cmd) {
      this.$refs.userImportDialog.show({
        userType: cmd,
        table: this.$refs.table
      });
    },
    onDetailsClick(user) {
      this.pushPage({
        path: '/user/details',
        params: { user },
        key: user.id
      });
    },
    onExportClick() {
      this.$message.info('正在处理导出，请稍等...');
      location.href = "api/user/export?" + qs.stringify({...this.$refs.userQuerier.getQueryParams(), ...this.searchForm});
    },
    changeCityAllowanceColVisible(queryParams) {
      let specialTypes = queryParams.specialTypes || [];
      specialTypes = typeof specialTypes == 'string' ? specialTypes.split(',') : specialTypes;
      if (specialTypes.includes('21')) {
        this.opColVisible = false;
        this.$nextTick(() => {
          this.cityAllowanceColVisible = true;
          setTimeout(() => {
            this.opColVisible = true;
          }, 100);
        });
      } else {
        this.cityAllowanceColVisible = false;
        this.$nextTick(() => {
          this.opColVisible = true;
        });
      }
    },
    getPageParams() {
      let query = this.$params.query;
      if (query) {
        query = typeof query == 'string' ? qs.parse(query) : query;
      } else {
        query = {};
      }
      return {...this.$params, query};
    }
  }
}
</script>
